/* 封装axios用于发送请求 */
import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from './storage'

// 创建一个新的axios实例
const request = axios.create({
  baseURL: 'http://interview-api-t.itheima.net/',
  timeout: 5000
})

// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    if (getToken()) {
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    // 数据剥离
    return response.data
  },
  function (error) {
    Message.error(error.response?.data.message)
    return Promise.reject(error)
  }
)

export default request
